package com.example;

import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;

import java.awt.Graphics2D;
import java.awt.Color;
import java.awt.Font;
import java.awt.image.BufferedImage;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;



@WebServlet("/image")
public class ImageServlet extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setHeader("refresh", "3");

        int i = (int)(new Random().nextFloat()*1000000);
        String num = Integer.toString(i);


        BufferedImage img = new BufferedImage(80, 20,BufferedImage.TYPE_3BYTE_BGR);
        Graphics2D graphics = (Graphics2D )img.getGraphics();
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, 80, 20);;
        graphics.setColor(Color.BLUE);
        graphics.setFont(new Font(null,Font.BOLD, 20));
        graphics.drawString(num, 0, 20);

        resp.setContentType("image/png");
        resp.setDateHeader("expires", -1);
        resp.setHeader("Cache-Contorl", "no-cache");
        resp.setHeader("Progam", "no-cache");
        
        ImageIO.write(img,"png",resp.getOutputStream());
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
